MybatisPlus两表关联查询MyBatis 您所在的位置:网站首页 mybatis-plus join MybatisPlus两表关联查询MyBatis

MybatisPlus两表关联查询MyBatis

2024-05-24 06:00| 来源: 网络整理| 查看: 265

MybatisPlus两表关联查询MyBatis-Plus-Join 介绍

mybatisplusjin

首先,让我们先了解一下MyBatis和MyBatis-Plus。MyBatis是一个流行的Java持久层框架,它提供了一种简单而强大的方式来将数据库操作与Java代码进行绑定。而MyBatis-Plus是基于MyBatis的增强工具,它提供了更多便捷的功能和特性,让我们能够更高效地进行数据库操作。

现在,让我们进入重头戏——MyBatis-Plus-Join!它是MyBatis-Plus框架中的一个强大功能,旨在简化数据库表的连接操作。你知道吗,通常在数据库中,我们会有多个表之间的关联关系。以学生和班级为例,一个班级可能有多个学生,而一个学生只属于一个班级。在过去,要实现学生和班级的数据关联查询,我们需要手动编写复杂的SQL语句。但是现在,有了MyBatis-Plus-Join,一切都变得轻松起来!

使用MyBatis-Plus-Join,你只需简单地定义实体之间的关系,然后让框架来为你处理连接查询。你可以像使用普通的实体类一样操作关联查询,而无需关心复杂的SQL语句。这大大简化了我们的开发工作,减少了出错的可能性。

而且,MyBatis-Plus-Join还支持多种类型的连接查询,包括内连接、左连接和右连接等。这样,无论是想要获取匹配的数据还是包含全部数据,我们都能轻松搞定。

总之,MyBatis-Plus-Join是一个让数据库表连接操作变得简单又高效的神奇工具。它让我们摆脱繁琐的SQL语句,以更直观的方式进行关联查询。如果你是一个热爱数据库操作的开发者,那么MyBatis-Plus-Join绝对是你不可或缺的利器!

使用 依赖引入 com.github.yulichang mybatis-plus-join-boot-starter 1.4.6 关联查询 baseMapper.selectJoinPage(page, StoreEntity.class, new MPJLambdaWrapper() .selectAll(StoreEntity.class) .select(DealerEntity::getDealerName) .leftJoin(DealerEntity.class, DealerEntity::getId, StoreEntity::getDistributorId) .eq(store.getStatus() != null, StoreEntity::getStatus, store.getStatus()));

说明:

StoreEntity.class是最终返回的DTO

new MPJLambdaWrapper()中的StoreEntity是主表查询的实体类

.selectAll(StoreEntity.class)是查询主表的全部字段

.select(DealerEntity::getDealerName)是查询字表的dealerName字段

.leftJoin(DealerEntity.class, DealerEntity::getId, StoreEntity::getDistributorId)是表关联,DealerEntity.class是字表实体类,DealerEntity::getId关联字表的字段,StoreEntity::getDistributorId关联主表的字段

.eq(store.getStatus() != null, StoreEntity::getStatus, store.getStatus())这个就是其他的条件查询啦,跟MP是一样的

以上执行SQL打印 select t.id, t.store_code, t.store_name, t.distributor_id, t.status, t.contact_person, t.contact_phone, t.store_location, t.position_lon, t.position_lat, t.create_by, t.create_time, t.update_by, t.update_time, t.dept_id, t.tenant_id, t.del_flag, # 这个是字表的字段 t1.dealer_name from tb_store t left join tb_dealer t1 on t1.id = t.distributor_id and t1.tenant_id = 1 where t.del_flag = '0' and t1.del_flag = '0' and t.tenant_id = 1 limit 10

是不是跟写关联查询的sql是一样的



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有